package web2023.team.homework_10_aop.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import web2023.team.homework_10_aop.entity.Login_info;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
@Repository
public class LoginInfoImpl implements LoginInfoDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Integer insertLoginInfo(Login_info loginInfo){
        //创建添加的sql语句
        String addsql = "insert into login_info values(null,?,?,?)";
        //调用jdbcTemplate.update实现添加,三个参数对应values(?,?,?)里的三个问号
        Object[] args = {loginInfo.getUsername(), loginInfo.getIp(), loginInfo.getTime()};
        try {
            int update = jdbcTemplate.update(addsql,args);
            //返回值update代表添加了几行
            //System.out.println(update);//1
            return update;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Login_info> allLoginInfo(){
        String sql = "select * from login_info";
        List<Login_info> login_infos = jdbcTemplate.query(sql, new MyRowMapper());
        return login_infos;
    }

}

class MyRowMapper implements RowMapper<Login_info> {

    @Override
    public Login_info mapRow(ResultSet rs, int num) throws SQLException {
        //从结果集里把数据得到
        String username = rs.getString("username");
        String ip  = rs.getString("ip");
        Timestamp time = rs.getTimestamp("time");
        //把数据封装到对象里
        Login_info loginInfo = new Login_info();
        loginInfo.setUsername(username);
        loginInfo.setIp(ip);
        loginInfo.setTime(time);
        return loginInfo;
    }

}